package NG::Sys::Cached::DBStore;
use strict;
use warnings;
use utf8;

use JSON::XS;

use NG::Sys::Cached::Common;
our @ISA = qw(NG::Sys::Cached::Common::Parent);

sub init {
	my $self = shift;
	$self->SUPER::init;
	unless($self->{pkey}){
		die "need pkey\n";
	}
	unless($self->{fields}){
		die "need fields\n";
	}
	unless($self->{table}){
		die "need table\n";
	}
	unless($self->{dbh}){
		die "need dbh\n";
	}

	@{$self->{hash_fields}}{@{$self->{fields}}} = (1) x @{$self->{fields}};
	if($self->{blobs}){
		$self->{hash_blobs} = { map {$_=>1} $self->check_fields_ary($self->{blobs}) };
	}else{
		$self->{hash_blobs} = {};
	}

	$self->{sth}{insert} = $self->{dbh}->prepare("insert into `".$self->{table}."` (".
					join(", ",map {"`".$_."`" } @{$self->{fields}}).
					") values (".
					join(", ",("?") x  @{$self->{fields}}).
					")");
	$self->{sth}{read} = $self->{dbh}->prepare("
		select * from `".$self->{table}."` where `".$self->{pkey}."`=?
		");
}
sub need_create {
	return undef;
}
sub check_field {
	my $self = shift;
	my $key = shift;
	return exists $self->{hash_fields}{$key} || die "unexists key'".$key."' checked\n";
}
sub check_fields_ary {
	my ($self,$keys) = @_;
	my $h = $self->{hash_fields};
	exists $h->{$_} || die "unexists key'".$_."' checked\n" for @$keys;
	return @$keys;
}
sub insert {
	my $self = shift;
	my $row = shift;
	if(scalar %{$self->{hash_blobs}}){
		for(@{$self->{blobs}}){
			defined($row->{$_}) and $row->{$_} = encode_json($row->{$_});
		}
	}
	$self->{sth}{insert}->execute(@{$row}{@{$self->{fields}}});
	return $self->{sth}{insert}{mysql_insertid};
}
sub get_row {
	my $self = shift;
	my $id = shift;
	
	$self->{sth}{read}->execute($id);
	my $list = $self->{sth}{read}->fetchall_arrayref({});
	my $row;
	if($row = shift @$list){
		if(scalar %{$self->{hash_blobs}}){
			for(@{$self->{blobs}}){
				defined $row->{$_} and $row->{$_} = decode_json($row->{$_});
			}
		}
	}
	return $row;
}

1;
